const { query } = require('../../../lib/db');
const { authenticateToken } = require('../../../lib/auth');
const { validate, todoCreateSchema } = require('../../../lib/validation');

async function handler(req, res) {
  try {
    switch (req.method) {
      case 'GET':
        return await getTodos(req, res);
      case 'POST':
        return await createTodo(req, res);
      default:
        return res.status(405).json({
          success: false,
          message: '方法不允许'
        });
    }
  } catch (error) {
    console.error('待办API错误:', error);
    res.status(500).json({
      success: false,
      message: '服务器内部错误'
    });
  }
}

// 获取待办列表
async function getTodos(req, res) {
  const {
    page = 1,
    limit = 10,
    status,
    priority
  } = req.query;

  const offset = (parseInt(page) - 1) * parseInt(limit);
  
  // 构建查询条件 - 用户只能查看自己的待办
  let whereConditions = ['user_id = ?'];
  let queryParams = [req.user.id];

  if (status) {
    whereConditions.push('status = ?');
    queryParams.push(status);
  }

  if (priority) {
    whereConditions.push('priority = ?');
    queryParams.push(priority);
  }

  const whereClause = `WHERE ${whereConditions.join(' AND ')}`;

  // 查询总数
  const countSql = `SELECT COUNT(*) as total FROM todos ${whereClause}`;
  const countResult = await query(countSql, queryParams);
  const total = countResult[0].total;

  // 查询数据
  const dataSql = `
    SELECT * FROM todos
    ${whereClause}
    ORDER BY 
      CASE WHEN status = 'pending' THEN 0 ELSE 1 END,
      CASE priority WHEN 'high' THEN 0 WHEN 'medium' THEN 1 ELSE 2 END,
      due_date ASC,
      created_at DESC
    LIMIT ? OFFSET ?
  `;
  
  const dataQueryParams = [...queryParams, parseInt(limit), offset];
  const todos = await query(dataSql, dataQueryParams);

  res.status(200).json({
    success: true,
    data: {
      todos,
      pagination: {
        page: parseInt(page),
        limit: parseInt(limit),
        total,
        pages: Math.ceil(total / parseInt(limit))
      }
    }
  });
}

// 创建待办
async function createTodo(req, res) {
  // 验证请求数据
  const validation = validate(todoCreateSchema, req.body);
  if (!validation.isValid) {
    return res.status(400).json({
      success: false,
      message: '请求数据验证失败',
      errors: validation.errors
    });
  }

  const todoData = validation.data;
  
  const insertSql = `
    INSERT INTO todos (user_id, title, description, priority, due_date) 
    VALUES (?, ?, ?, ?, ?)
  `;

  const insertParams = [
    req.user.id,
    todoData.title,
    todoData.description || null,
    todoData.priority,
    todoData.due_date || null
  ];

  const result = await query(insertSql, insertParams);

  // 查询创建的待办详情
  const createdTodo = await query(
    'SELECT * FROM todos WHERE id = ?',
    [result.insertId]
  );

  res.status(201).json({
    success: true,
    message: '待办创建成功',
    data: createdTodo[0]
  });
}

export default authenticateToken(handler);